<template>
  <div class="system-home">
  

    <!-- 第一行（5列） -->
    <div class="flex-row">
      <div class="flex-col bg-yellow">
        <div style="display: flex; flex-direction: column; padding: 1rem;gap: 1rem">
          <div style="color: white; font-weight: bold; text-align: left;font-size: 2vh;">设备总数 </div>
          <div style="color: white; text-align: right;">9个</div>
        </div>
      </div>
      <div class="flex-col bg-orange">
        <div style="display: flex; flex-direction: column; padding: 1rem;gap: 1rem">
          <div style="color: white; font-weight: bold; text-align: left;font-size: 2vh;">在线设备数 </div>
          <div style="color: white; text-align: right;">5个</div>
        </div>
      </div>
      <div class="flex-col bg-pink">
        <div style="display: flex; flex-direction: column; padding: 1rem;gap: 1rem">
          <div style="color: white; font-weight: bold; text-align: left;font-size: 2vh;">离线设备数 </div>
          <div style="color: white; text-align: right;">4个</div>
        </div>
      </div>
      <div class="flex-col bg-red">
        <div style="display: flex; flex-direction: column; padding: 1rem;gap: 1rem">
          <div style="color: white; font-weight: bold; text-align: left;font-size: 2vh;">工程总数 </div>
          <div style="color: white; text-align: right;">7个</div>
        </div>
      </div>
      <div class="flex-col bg-purple">
        <div style="display: flex; flex-direction: column; padding: 1rem;gap: 1rem">
          <div style="color: white; font-weight: bold; text-align: left;font-size: 2vh;">工单总数</div>
          <div style="color: white; text-align: right;">39个</div>
        </div>
      </div>
    </div>

    <!-- 合并区域 -->
    <div class="merged-area">
      <!-- 合并后的第一列（跨两行） -->
      <div class="merged-col-left">
        <div ref="map" style="height: 540px; border: 1px solid #ddd;"></div>
      </div>

      <!-- 右侧正常列 -->
      <div class="right-cols">
        <!-- 第二行右侧两列 -->
        <div class="flex-row">
          <div class="flex-col" style="border: 1px solid #ddd; height: 250px;">
            <div ref="left2" style="height: 150px;"></div>
          </div>
          <div class="flex-col" style="border: 1px solid #ddd; height: 250px;">
            <!-- 折线图标题 -->
            <div>
              <Title :title="lineTitle"></Title>
            </div>
            <!-- 折线图容器 -->
            <div ref="left1" style="height: 150px; margin-top: 15px;"></div>
          </div>
        </div>

        <!-- 第三行右侧合并的两列 -->
        <div class="flex-row">
          <div class="merged-col-right">
            <div class="flex-col" style="border: 1px solid #ddd; height: 250px;">
              <div>
                <Title :title="title"></Title>
              </div>
              <div ref="right2" style="height: 150px; width: 100%;"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Pie } from '@antv/g2plot';
import { Line } from '@antv/g2plot';
import { Bar } from '@antv/g2plot';
import { get } from '@/utils/request';
import { mapState } from 'vuex';
import moment from 'moment';

export default {
  data() {
    return {
      title: '环境工程',
      empData: [],
      lineTitle: '实时温度曲线',
      params: {
        page: 1,
        pageSize: 51
      },
      tempData: [],
      line: null,
      barChart: null,
      chartData: [
        { year: '山西农大', value: 1 },
        { year: '太原理工', value: 2 },
        { year: '中北大学', value: 0 },
        { year: '兰州理工', value: 2 },
      ]
    };
  },
  computed: {
    ...mapState(['ed'])
  },
  // 侦听器
  watch: {
    ed: {
      handler(n, o) {
        console.log(n, '333');
        this.params.device_id = n.device_id;
        this.params.engineer_id = n.engineer_id;
        this.getTemData();
        // 重新渲染图表
        if (this.line) {
          this.line.changeData(this.tempData);
        }
      },
      // 开启深度监听
      deep: true
    }
  },
  methods: {
    // 封装加载地图方法
    async loadMap() {
      try {
        window._AMapSecurityConfig = {
          securityJsCode: "0b7a44c42a4074b3a5bdb6cc22658d7b",
        };
        const script = document.createElement('script');
        script.src = 'https://webapi.amap.com/loader.js';
        script.onload = () => {
          AMapLoader.load({
            key: "3fe72930cd02227dca02822a3ce0c67d", // 申请好的Web端开发者 Key，调用 load 时必填
            version: "2.0", // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
          })
          .then((AMap) => {
            const map = new AMap.Map(this.$refs.map);
          })
          .catch((e) => {
            console.error(e); // 加载错误提示
          });
        };
        document.head.appendChild(script);
      } catch (error) {
        console.error('Error loading map:', error);
      }
    },
    loadPie() {
      try {
        const piePlot = new Pie(this.$refs.left2, {
          appendPadding: 5, // 减小内边距
          data: this.empData,
          angleField: 'value',
          colorField: 'type',
          color: ({ type }) => {
            if (type == '在线') {
              return '#a2a6ec'
            }
            return 'pink'
          },
          radius: 0.95, // 增大半径，让饼图更大
          legend: {
            itemName: {
              style: {
                fill: 'black'
              }
            }
          },
          label: {
            type: 'outer',
            // content: '{name} {percentage}',
            content: '{name}',
            style: {
              fill: 'black'
            }
          },
          interactions: [{ type: 'pie-legend-active' }, { type: 'element-active' }],
        });

        piePlot.render();
      } catch (error) {
        console.error('Error rendering pie chart:', error);
      }
    },
    async getEmpData() {
      try {
        let res = await get('/dashboard/queryDeviceOnlineNumber');
        console.log(res, '获取响应');
        this.empData = res.data;
      } catch (error) {
        console.error('Error getting device online data:', error);
      }
    },
    // 封装加载图表方法
    loadLine() {
      try {
        // 3.创建图表实例  图表容器id 图表配置项对象 
        this.line = new Line(this.$refs.left1, {
          data: this.tempData,
          xField: 'insert_time',
          yField: 'temperature',
          // x轴样式 
          xAxis: {
            label: {
              rotate: -45,
              style: {
                fill: 'black' // 修改为黑色
              }
            }
          },
          // y轴字段样式
          yAxis: {
            label: {
              style: {
                fill: 'black' // 修改为黑色
              }
            }
          },

          label: {
            style: {
              fill: 'black', // 修改为黑色
              // fontSize:20
            }
          },

          // 设置折线图动画方式
          animation: {
            appear: {
              animation: 'wave-in',
              duration: 5000,
            },
          },
          // 设置曲线是否平滑
          smooth: true,
          point: {
            size: 5,
            shape: 'diamond',
            style: {
              fill: 'white',
              stroke: '#5B8FF9',
              lineWidth: 2,
            },
          },
          // tooltip: { showMarkers: false },
          // 更改提示框的样式
          tooltip: {
            domStyles: {
              "g2-tooltip": {
                backgroundColor: '#147',
                color: 'black', // 修改为黑色
                fontSize: 20
              }
            }
          },
          state: {
            active: {
              style: {
                shadowBlur: 4,
                stroke: '#000',
                fill: 'red',
              },
            },
          },
          interactions: [{ type: 'marker-active' }],
        });
        // 4.图表渲染 
        this.line.render();
      } catch (error) {
        console.error('Error rendering line chart:', error);
      }
    },
    // 封装获取温度数据方法 
    async getTemData() {
      try {
        let res = await get('/dashboard/pageQueryTodayData', this.params);
        console.log(res, '获取响应');
        // 将后端获取数据设置给 tempData
        //    this.tempData = res.data.list;
        // 由于时间是时间戳 需要处理成小时:分钟格式 
        res.data.list.forEach(function (item, index, arr) {
          // 由于数据过高 导致y轴坐标混乱 需要设置第一条数据值低点
          arr[0].temperature = 15.4;
          // 对每条数据时间进行处理 处理成小时:分钟
          item.insert_time = moment(item.insert_time).format('HH:mm');
        });
        let temp = [];
        res.data.list.forEach((item, index, arr) => {
          // 每隔10条选取一条 因为监测数据可能1分钟采取10条一样数据 
          if (index % 10 == 0) {
            temp.push(arr[index])
          }
        })
        this.tempData = temp;
      } catch (error) {
        console.error('Error getting temperature data:', error);
      }
    },
    initChart() {
      try {
        this.barChart = new Bar(this.$refs.right2, {
          data: this.chartData,
          xField: 'value',
          yField: 'year',
          seriesField: 'year',
          height: 150, // 设置图表高度
          legend: {
            position: 'top-left',
          },
          // 添加响应式配置
          responsive: true,
          // 自定义柱状样式
          barStyle: {
            fillOpacity: 0.8,
          },
          // 添加动画效果
          animation: {
            appear: {
              animation: 'scale-in-x'
            }
          }
        });

        this.barChart.render();
      } catch (error) {
        console.error('Error rendering bar chart:', error);
      }
    }
  },
  async mounted() {
    try {
      await this.getEmpData();
      this.loadPie();
      await this.getTemData();
      this.loadLine();
      await this.loadMap();
      this.initChart();
    } catch (error) {
      console.error('Error in mounted hook:', error);
    }
  },
  beforeDestroy() {
    // 组件销毁时销毁图表实例
    if (this.barChart) {
      this.barChart.destroy();
    }
    if (this.line) {
      this.line.destroy();
    }
  }
};
</script>

<style scoped>
.system-home {
  padding: 20px;
}

h1 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.flex-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.flex-col {
  flex: 1;
  height: 150px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #333;
  font-size: 18px;
}

/* 第一行颜色样式 */
.bg-yellow {
  background: #f1e25b;
}

.bg-orange {
  background: #f0af4f;
}

.bg-pink {
  background: #f8407e;
}

.bg-red {
  background: #ef4135;
}

.bg-purple {
  background: #973ef6e8;
}

/* 合并区域样式 */
.merged-area {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.merged-col-left {
  flex: 1;
}

.right-cols {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.merged-col-right {
  flex: 1;
  display: flex;
  gap: 20px;
}
</style>